import numpy as np
import time

np.random.seed(42)
def generate_weight_matrix(rows,cols):
    """生成指定大小的随机矩阵，元素值范围为-1,1"""
    return np.random.uniform(-1,1,(rows,cols))

def quantize_int8(matrix):
    max_val = np.max(np.abs(matrix))
    scale = max_val / 127
    quantized = np.clip(np.round(matrix/scale),-127,127).astype(np.int8)
    return quantized,scale

def dequantize_int8(quantized,scale):
    return quantized.astype(np.float32) *scale

def low_rank_compensation(matrix,rank=8):
    U,S,Vt = np.linalg.svd(matrix,full_matrices=False)
    A = U[:,:rank] = np.sqrt(S[:rank])
    B = (np.sqrt(S[:rank]) *Vt[:rank,:])
    compensation = np.dot(A,B)
    return compensation,A,B
